﻿Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports ISNet.WebUI.WebGrid
Imports System.Data
Imports ISNet.WebUI.WebTreeView
Imports log4net

Partial Class B03_CheckBudgetLimit
    Inherits System.Web.UI.Page

    Dim cmmtcode As String = ""
    Public CmtNameTxt As String = ""
    Public CmtTxt As String = ""
    Public AlertText As String
    Public ScriptText As String
    Public price As String = ""
    Public CodeTxt As String = ""
    Dim pricehash As New Hashtable
    Public PrjTxt As String = ""

    Private Shared logger As ILog = LogManager.GetLogger("B03_CheckBudgetLimit")

    Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
        WebCombo3.EncodeOutput = True
    End Sub
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Session("users") Is Nothing Then
            Response.Redirect("LoginForm.aspx")
        End If
        
        'If Session("Versions").ToString = "1" Or Session("Versions").ToString = "2" Or Session("Versions").ToString = "3" Or Session("Versions").ToString = "4" Then
        '    AlertText = "<script> alert('ฟอร์ม Review วงเงินงบประมาณ ออกแบบให้ฝบป. ใช้ในการวิเคราะห์ข้อมูลงบประมาณแบบไม่ลงรายละเอียดเท่านั้น'); window.location = 'Selector.aspx?type=45';</script>"
        'End If
        cmmtcode = Session("CMMT_OT_CODE")
        'Session("Versions") = 1
        VersionTxt.Text = Session("Versions")
        'Session("users") = "bb9222"
        'Session.Add("PlanYear", 2557)
        PlanYearsTxt.Text = Val(Session("PlanYear"))

        GenerateValues()

        If IsPostBack = False Then
            Session.Remove("Search")
            Session.Remove("search_fctr")



            Label1.Text = "ระบบจัดทำงบประมาณ >> จัดทำงบประมาณ >> แบบฟอร์ม Review วงเงินงบประมาณ"
            'If Session("Versions") = 1 Then
            '    div1.Visible = False
            '    div2.Visible = False
            '    SearhBtn.Visible = False
            '    WebTreeView1.Visible = False
            '    WebTreeView2.Visible = False
            '    WebTreeView3.Visible = False
            'End If
            'Response.Write(" Project " & Date.Now)
            Dim adapter As New AttachmentTableAdapters.ProjectsTableAdapter
            Dim data As New Attachment.ProjectsDataTable
            'data = adapter.GetDataByPlanYear(Val(Session("PlanYear")))
            Dim sql = ""
            Dim prefil As String = ""
            prefil = Session("prefilter")
            sql += " WHERE 1 = 1 "
            sql += " AND planYear = " & PlanYearsTxt.Text & " "
            If prefil <> "" Then
                sql += " AND FundCenter_FundCenterCode IN (" & prefil & ") "
            End If

            sql += " UNION  "
            sql += " SELECT ProjectCode, PlanYear, (Description) AS Description , CreatedDate, UpdatedDate, CreatedBy, UpdatedBy, FundCenter_FundCenterCode "
            sql += " FROM Projects AS Projects1 "
            sql += " WHERE Projects1.FundCenter_FundCenterCode IS NULL "
            sql += " AND Projects1.PlanYear = " & PlanYearsTxt.Text & " "

            adapter.GetDataByFilter(data, sql)

            ms8.DataValueField = "ProjectCode"
            ms8.DataTextField = "Description"
            ms8.DataSource = data
            ms8.DataBind()

            'Response.Write(" Cmmt " & Date.Now)
            Dim adapter2 As New MassChangeDSTableAdapters.CmmtsTableAdapter
            Dim datatable2 As New MassChangeDS.CmmtsDataTable
            datatable2 = adapter2.GetData(Session("PlanYear"))
            ms9.DataValueField = "CmmtCode"
            ms9.DataTextField = "Description"
            ms9.DataSource = datatable2
            ms9.DataBind()

        End If
        If WebGrid1.IsFlyPostBack = False Then
            'Response.Write("FCTR" & Date.Now)
            'PlotNode()
            'Response.Write(" " & Date.Now)
            Dim adap As New CheckBudgetLimitTableAdapters.AppConfigsTableAdapter
            Dim dataApp As New CheckBudgetLimit.AppConfigsDataTable
            dataApp = adap.GetData(Val(PlanYearsTxt.Text))
            'Alert(dataApp.Count)
            If dataApp.Count > 0 Then
                Dim id As Integer = 0
                For Each row As CheckBudgetLimit.AppConfigsRow In dataApp
                    id = id + 1
                    CmtTxt += "CmtList[" & id & "]='" & row.Value & "';"
                    CmtNameTxt += "CmtNameList[" & id & "]='" & row.Description & "';"
                Next

            End If

            Dim adap2 As New BasicDataTableAdapters.ActivityTypesTableAdapter
            Dim dt2 As New BasicData.ActivityTypesDataTable
            dt2 = adap2.GetDataByPlanYear(Val(Session("PlanYear")))
            Dim i As Integer = 0
            'cmt_hash.Clear()
            For Each row As BasicData.ActivityTypesRow In dt2
                price += "CodeArray[" & i & "]='" & row.ActivityTypeCode & "';"
                price += "Price[" & i & "]='" & row.Price & "';"
                i += 1
                pricehash.Remove(row.ActivityTypeCode)
                pricehash.Add(row.ActivityTypeCode, row.Price)
            Next
            Dim adap3 As New AttachmentTableAdapters.ProjectsTableAdapter
            Dim data3 As New Attachment.ProjectsDataTable
            Dim sql3 = ""
            sql3 += " SELECT ProjectCode, PlanYear, (Description) AS Description , CreatedDate, UpdatedDate, CreatedBy, UpdatedBy, FundCenter_FundCenterCode "
            sql3 += " FROM Projects"
            sql3 += " WHERE Projects.FundCenter_FundCenterCode IS NULL "
            sql3 += " AND Projects.PlanYear = " & PlanYearsTxt.Text & " "
            'Response.Write(sql3)
            adap3.GetDataByFilter2(data3, sql3)
            Dim n As Integer = 0
            For Each row As Attachment.ProjectsRow In data3
                PrjTxt += "PrjArray[" & n & "]='" & row.ProjectCode & "';"
                n = n + 1
            Next
        End If

        'Response.Write(" PageLoadEnd " & Date.Now)
    End Sub

    Protected Sub WebGrid1_InitializeDataSource(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.DataSourceEventArgs) Handles WebGrid1.InitializeDataSource
        Dim adapter As New CheckBudgetLimitTableAdapters.BudgetDetailsTableAdapter
        Dim datatable As New CheckBudgetLimit.BudgetDetailsDataTable
        adapter.SetCommandTimeOut(ConfigurationManager.AppSettings("QueryTimeOut"))

        Dim prefil As String = ""
        prefil = Session("prefilter")
        'If Session("Versions") > 1 Then
        If IsPostBack = True And Session("Search") = "true" Then
            Dim sql As String = ""
            Dim fctr As String = ""
            fctr = Session("search_fctr")
            If TabContainer1.ActiveTab.ID = TabPanel1.ID Then
                sql += " WHERE 1 = 1 "
                'sql += " WHERE BudgetDetails.FundCenter_FundCenterCode BETWEEN " & Val(WebCombo1.Value) & " AND " & Val(WebCombo2.Value

                If hdf1.Value.ToString <> "" Then
                    sql += " AND BudgetDetails.Project_ProjectCode IN ("
                    Dim Numx() As String = hdf1.Value.Split(",")
                    For i = 0 To Numx.Length - 1
                        If Numx(i).Trim <> "" Then
                            If i <> 0 Then
                                sql += ","
                            End If
                            sql += "'" & Numx(i).ToString & "'"
                        End If

                    Next
                    sql += ") "
                End If

                If TabContainer2.ActiveTab.ID = TabPanel3.ID Then
                    If WebCombo4.Value <> "" And WebCombo5.Value <> "" Then
                        sql += " AND BudgetDetails.Cmmt_CmmtCode Between "
                        sql += WebCombo4.Value & " AND "
                        sql += WebCombo5.Value & " "
                    ElseIf WebCombo4.Value <> "" And WebCombo5.Value = "" Then
                        sql += " AND BudgetDetails.Cmmt_CmmtCode = "
                        sql += WebCombo4.Value & " "
                    ElseIf WebCombo4.Value = "" And WebCombo5.Value <> "" Then
                        sql += " AND BudgetDetails.Cmmt_CmmtCode = "
                        sql += WebCombo5.Value & " "
                    End If
                ElseIf TabContainer2.ActiveTab.ID = TabPanel4.ID Then
                    If hdf2.Value.ToString <> "" Then
                        sql += " AND BudgetDetails.Cmmt_CmmtCode IN ("
                        Dim Numx As Array = hdf2.Value.Split(",")
                        For i = 0 To Numx.Length - 1
                            If Val(Numx(i)) <> 0 Then
                                If i <> 0 Then
                                    sql += ","
                                End If
                                sql += Numx(i).ToString
                            End If

                        Next
                        sql += ") "
                    End If
                End If

                sql += " AND BudgetDetails.Version = '" & VersionTxt.Text & "'"
                ' sql += " AND FormId = 'F01' "
                'sql += " AND BudgetDetails.Project_ProjectCode IS NOT NULL "
                If fctr <> "" Then
                    If fctr <> "0" Then
                        sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & fctr & ") "
                    Else
                        sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & prefil & ") "
                    End If
                Else
                    If prefil <> "" Then
                        sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & prefil & ") "

                    End If

                End If
                sql += " AND BudgetDetails.Project_ProjectCode IS NOT NULL "
                'sql += " AND (BudgetDetails.FormId = 'F01' OR BudgetDetails.FormId = 'F02' OR BudgetDetails.FormId = 'F03' OR BudgetDetails.FormId = 'F04' "
                'sql += " OR BudgetDetails.FormId = 'F05' OR BudgetDetails.FormId = 'F06' OR BudgetDetails.FormId = 'F07' OR BudgetDetails.FormId = 'F08' "
                'sql += " OR BudgetDetails.FormId = 'F07' OR BudgetDetails.FormId = 'F08' OR BudgetDetails.FormId = 'F09' OR BudgetDetails.FormId = 'F10' "
                'sql += " OR BudgetDetails.FormId = 'B03') "
                sql += " AND BudgetDetails.PlanYear = " & PlanYearsTxt.Text & " "
                sql += " ORDER BY BudgetDetails.FundCenter_FundCenterCode,BudgetDetails.Id"
                adapter.GetDataByFilter(datatable, sql)
                'Response.Write(sql)

            ElseIf TabContainer1.ActiveTab.ID = TabPanel2.ID Then
                sql += " WHERE 1 = 1 "
                'sql += " WHERE BudgetDetails.FundCenter_FundCenterCode IN (SELECT FundCenter_FundCenterCode FROM FundCenterHierarchies "
                'sql += " WHERE FundCenter_FundCenterCode = " & Val(WebCombo3.Value) & " OR ParentFundCenterHierarchy_Id = " & Val(WebCombo3.Value) & ") "
                If hdf1.Value.ToString <> "" Then
                    sql += " AND BudgetDetails.Project_ProjectCode IN ("
                    Dim Numx() As String = hdf1.Value.Split(",")
                    For i = 0 To Numx.Length - 1
                        If Numx(i).Trim <> "" Then
                            If i <> 0 Then
                                sql += ","
                            End If
                            sql += "'" & Numx(i).ToString & "'"
                        End If
                    Next
                    sql += ") "
                End If

                If TabContainer2.ActiveTab.ID = TabPanel3.ID Then
                    If WebCombo4.Value <> "" And WebCombo5.Value <> "" Then
                        sql += " AND BudgetDetails.Cmmt_CmmtCode Between "
                        sql += WebCombo4.Value & " AND "
                        sql += WebCombo5.Value & " "
                    ElseIf WebCombo4.Value <> "" And WebCombo5.Value = "" Then
                        sql += " AND BudgetDetails.Cmmt_CmmtCode = "
                        sql += WebCombo4.Value & " "
                    ElseIf WebCombo4.Value = "" And WebCombo5.Value <> "" Then
                        sql += " AND BudgetDetails.Cmmt_CmmtCode = "
                        sql += WebCombo5.Value & " "
                    End If
                ElseIf TabContainer2.ActiveTab.ID = TabPanel4.ID Then
                    If hdf2.Value.ToString <> "" Then
                        sql += " AND BudgetDetails.Cmmt_CmmtCode IN ("
                        Dim Numx As Array = hdf2.Value.Split(",")
                        For i = 0 To Numx.Length - 1
                            If Val(Numx(i)) <> 0 Then
                                If i <> 0 Then
                                    sql += ","
                                End If
                                sql += Numx(i).ToString
                            End If

                        Next
                        sql += ") "
                    End If
                End If

                sql += " AND BudgetDetails.Version = '" & VersionTxt.Text & "'"
                '  sql += " AND FormId = 'F01' "
                'sql += " AND BudgetDetails.Project_ProjectCode IS NOT NULL "
                If fctr <> "" Then
                    sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & fctr & ") "
                Else
                    sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & prefil & ") "
                End If
                'sql += " AND BudgetDetails.Project_ProjectCode IS NOT NULL "
                'sql += " AND (BudgetDetails.FormId = 'F01' OR BudgetDetails.FormId = 'F02' OR BudgetDetails.FormId = 'F03' OR BudgetDetails.FormId = 'F04' "
                'sql += " OR BudgetDetails.FormId = 'F05' OR BudgetDetails.FormId = 'F06' OR BudgetDetails.FormId = 'F07' OR BudgetDetails.FormId = 'F08' "
                'sql += " OR BudgetDetails.FormId = 'F07' OR BudgetDetails.FormId = 'F08' OR BudgetDetails.FormId = 'F09' OR BudgetDetails.FormId = 'F10' "
                'sql += " OR BudgetDetails.FormId = 'B03') "
                sql += " AND BudgetDetails.PlanYear = " & PlanYearsTxt.Text & " "
                sql += " ORDER BY BudgetDetails.FundCenter_FundCenterCode,BudgetDetails.Id"
                adapter.GetDataByFilter(datatable, sql)
                'Response.Write(sql)

            End If

            If datatable.Rows.Count > 0 Then
                'Response.Write(sql)
                datatable.Columns("PlanYear").AllowDBNull = True
                datatable.Columns("BaseYear").AllowDBNull = True
                datatable.Columns("Version").AllowDBNull = True
                datatable.Columns("FundCenter_FundCenterCode").AllowDBNull = True
                datatable.Columns("OldAssetNo").AllowDBNull = True
                datatable.Columns("FundCenter_PlanYear").AllowDBNull = True
                datatable.Columns("CmmtCode").AllowDBNull = True
                datatable.Columns("Id").ReadOnly = False

                datatable.Columns("Id").ReadOnly = False

                'Response.Write(Val(Session("FCTR")))

                CountResult.Text = "จำนวนรายการ : " & datatable.Count.ToString
                Dim sumAmount As Object = datatable.Compute("SUM(Amount)", "")
                Dim sumres As Decimal = 0
                If Not sumAmount.Equals(DBNull.Value) Then
                    sumres = sumAmount
                End If
                'Dim sumres As Decimal = datatable.Compute("SUM(Amount)", "")
                SumResult.Text = "จำนวนเงินรวม : " & Format(sumres, "#,##0.##")
                e.DataSource = datatable
            Else
                CountResult.Text = "จำนวนรายการ : " & "0"
                SumResult.Text = "จำนวนเงินรวม : " & Format(0, "#,##0.##")
            End If



            'datatable = adapter.GetDataByMultiple(Val(Session("PlanYear")), Val(Session("Versions")), Session("users"))
        Else
            Dim sql As String = ""

            sql += " WHERE 1 = 1 "
            'sql += " WHERE BudgetDetails.FundCenter_FundCenterCode BETWEEN " & Val(WebCombo1.Value) & " AND " & Val(WebCombo2.Value)
            sql += " AND BudgetDetails.Version = '" & VersionTxt.Text & "'"
            'sql += " AND FormId = 'F01' "
            ' sql += " AND BudgetDetails.Project_ProjectCode IS NOT NULL "
            If prefil <> "" Then
                sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & prefil & ") "
            End If
            'sql += " AND BudgetDetails.Project_ProjectCode IS NOT NULL "
            'sql += " AND (BudgetDetails.FormId = 'F01' OR BudgetDetails.FormId = 'F02' OR BudgetDetails.FormId = 'F03' OR BudgetDetails.FormId = 'F04' "
            'sql += " OR BudgetDetails.FormId = 'F05' OR BudgetDetails.FormId = 'F06' OR BudgetDetails.FormId = 'F07' OR BudgetDetails.FormId = 'F08' "
            'sql += " OR BudgetDetails.FormId = 'F07' OR BudgetDetails.FormId = 'F08' OR BudgetDetails.FormId = 'F09' OR BudgetDetails.FormId = 'F10' "
            'sql += " OR BudgetDetails.FormId = 'B03') "
            sql += " AND BudgetDetails.PlanYear = " & PlanYearsTxt.Text & " "
            sql += " ORDER BY BudgetDetails.FundCenter_FundCenterCode,BudgetDetails.Id"
            adapter.GetDataByFilter(datatable, sql)
            'Response.Write(sql)
            'datatable = adapter.GetDataByMultiple2(Val(Session("PlanYear")), Val(Session("Versions")), Session("users"))
            If datatable.Rows.Count > 0 Then
                datatable.Columns("PlanYear").AllowDBNull = True
                datatable.Columns("BaseYear").AllowDBNull = True
                datatable.Columns("Version").AllowDBNull = True
                datatable.Columns("FundCenter_FundCenterCode").AllowDBNull = True
                datatable.Columns("OldAssetNo").AllowDBNull = True
                datatable.Columns("FundCenter_PlanYear").AllowDBNull = True
                datatable.Columns("CmmtCode").AllowDBNull = True
                datatable.Columns("Id").ReadOnly = False

                'Response.Write(Val(Session("FCTR")))
                CountResult.Text = "จำนวนรายการ : " & datatable.Count.ToString
                Dim sumAmount As Object = datatable.Compute("SUM(Amount)", "")
                Dim sumres As Decimal = 0
                If Not sumAmount.Equals(DBNull.Value) Then
                    sumres = sumAmount
                End If
                'Dim sumres As Decimal = datatable.Compute("SUM(Amount)", "")
                SumResult.Text = "จำนวนเงินรวม : " & Format(sumres, "#,##0.##")
                e.DataSource = datatable
            Else
                CountResult.Text = "จำนวนรายการ : " & "0"
                SumResult.Text = "จำนวนเงินรวม : " & Format(0, "#,##0.##")
            End If

            'Response.Write(sql)
        End If
    End Sub

    Protected Sub WebGrid1_InitializeRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)
        'Exit Sub
        'If e.Row.Type = RowType.Record Then

        e.Row.Cells(0).ForceNoEdit = True
        e.Row.Cells(1).ForceNoEdit = True
        e.Row.Cells(3).ForceNoEdit = True
        e.Row.Cells(4).ForceNoEdit = True
        'e.Row.Cells(5).ForceNoEdit = True
        'e.Row.Cells(6).ForceNoEdit = True
        e.Row.Cells(7).ForceNoEdit = True
        e.Row.Cells(8).ForceNoEdit = True
        'e.Row.Cells(9).ForceNoEdit = True
        e.Row.Cells(10).ForceNoEdit = True
        e.Row.Cells(11).ForceNoEdit = True
        'e.Row.Cells(15).ForceNoEdit = True
        'Dim funCenterPro As String = e.Row.GetDataRow("Projects_FundCenterCode2")
        'If funCenterPro = "0" Then
        '    e.Row.Cells(16).ForceNoEdit = True
        '    e.Row.Cells(16).Style.BackColor = Drawing.Color.Gray
        'End If
        'End If

        If e.Row.Type = RowType.Record Then
            Dim cells As WebGridCellCollection = e.Row.Cells
            Dim dr As DataRowView = DirectCast(e.Row.DataRow, DataRowView)
            Dim formid As String = dr("FormId").ToString()
            If formid = "F04" Then
                e.Row.Cells(9).ForceNoEdit = True
                e.Row.Cells(5).ForceNoEdit = False
                e.Row.Cells(6).ForceNoEdit = False
                e.Row.Cells(2).ForceNoEdit = False

                e.Row.Cells(5).Style.BackColor = Drawing.Color.Empty
                e.Row.Cells(6).Style.BackColor = Drawing.Color.Empty
                e.Row.Cells(2).Style.BackColor = Drawing.Color.Empty
                e.Row.Cells(9).Style.BackColor = System.Drawing.ColorTranslator.FromHtml("#a0a0a0")
            Else
                e.Row.Cells(9).ForceNoEdit = False
                e.Row.Cells(5).ForceNoEdit = True
                e.Row.Cells(6).ForceNoEdit = True
                e.Row.Cells(2).ForceNoEdit = True

                e.Row.Cells(5).Style.BackColor = System.Drawing.ColorTranslator.FromHtml("#a0a0a0")
                e.Row.Cells(6).Style.BackColor = System.Drawing.ColorTranslator.FromHtml("#a0a0a0")
                e.Row.Cells(2).Style.BackColor = System.Drawing.ColorTranslator.FromHtml("#a0a0a0")
                e.Row.Cells(9).Style.BackColor = Drawing.Color.Empty
            End If
            If IsDBNull(dr("Project_FundcenterCode")) = True Then
                e.Row.Cells(12).ForceNoEdit = True
            Else
                If dr("Project_FundcenterCode") = "" Then
                    e.Row.Cells(12).ForceNoEdit = True
                End If
            End If
            If IsDBNull(dr("Project_ProjectCode")) = True Then
                e.Row.Cells(12).ForceNoEdit = True
            End If
        End If

    End Sub

    Protected Sub FundCenterCombo_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles FundCenterCombo.InitializeDataSource
        Dim ds As New DataSet
        'If Session("Versions") > 1 Then
        If IsPostBack = True And Session("Search") = "true" Then
            Dim fctr As String = ""
            fctr = Session("search_fctr")
            Dim adap As New BasicDataTableAdapters.FCTR_Child2TableAdapter
            Dim dt As New BasicData.FCTR_Child2DataTable
            Dim sql = ""
            sql += " WHERE 1 = 1 "
            sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FundCenters.PlanYear = " & Val(Session("PlanYear"))
            If fctr <> "" Then
                sql += " AND fctr_view.FundCenterCode IN (" & fctr & ") "
            End If
            sql += " and FundCenterHierarchies.PlanYear = " & Val(Session("PlanYear")) & " "
            sql += "ORDER BY [Level] ASC, FundCenterCode ASC"
            adap.GetDataByFilter(dt, sql)
            e.DataSource = dt
            'Response.Write(sql & "<br />")
        Else
            'ds = PublicFunction.GetChild2(Session("users"))
            'ds.Tables(0).DefaultView.Sort = "FundCenterCode ASC"
            'e.DataSource = ds
            Dim adap As New BasicDataTableAdapters.FCTR_Child2TableAdapter
            Dim dt As New BasicData.FCTR_Child2DataTable
            Dim sql = ""
            Dim prefil As String = ""
            prefil = Session("prefilter")
            sql += " WHERE 1 = 1 "
            sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FundCenters.PlanYear = " & Val(Session("PlanYear"))
            If prefil <> "" Then
                sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
            End If
            sql += " and FundCenterHierarchies.PlanYear = " & Val(Session("PlanYear")) & " "
            sql += "ORDER BY [Level] ASC, FundCenterCode ASC"
            adap.GetDataByFilter(dt, sql)
            e.DataSource = dt
        End If

    End Sub

    Protected Sub CmmtCombo_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles CmmtCombo.InitializeDataSource
        Dim adap As New MassChangeDSTableAdapters.CmmtsTableAdapter
        Dim dt As New MassChangeDS.CmmtsDataTable
        dt = adap.GetData(Val(Session("PlanYear")))
        e.DataSource = dt

    End Sub

    Protected Sub ProjectCombo_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles ProjectCombo.InitializeDataSource
        Dim adap As New BasicDataTableAdapters.Projects1TableAdapter
        Dim dt As New BasicData.Projects1DataTable
        Dim dt2 As New BasicData.Projects1DataTable
        Dim dt3 As New BasicData.Projects1DataTable
        Dim dt4 As New BasicData.Projects1DataTable
        dt = adap.GetDataByPrefix(Val(Session("PlanYear")), "P")
        dt2 = adap.GetDataByPrefix(Val(Session("PlanYear")), "D")

        dt3 = adap.GetDataByFCTRnull(Val(Session("PlanYear")), "P")
        dt4 = adap.GetDataByFCTRnull(Val(Session("PlanYear")), "D")

        dt.Merge(dt2)

        Dim prefil As String = Session("prefilter")

        Dim fadap As New FormLockDSTableAdapters.FundCentersTableAdapter
        Dim fdt As New FormLockDS.FundCentersDataTable
        fadap.GetDataByFilter(fdt, prefil)
        For Each fitem As FormLockDS.FundCentersRow In fdt
            For Each item As BasicData.Projects1Row In dt3
                item.FundCenterCode = fitem.FundCenter_FundCenterCode
            Next
            dt.Merge(dt3)
        Next

        fadap.GetDataByFilter(fdt, prefil)
        For Each fitem2 As FormLockDS.FundCentersRow In fdt
            For Each item2 As BasicData.Projects1Row In dt4
                item2.FundCenterCode = fitem2.FundCenter_FundCenterCode
            Next
            dt.Merge(dt4)
        Next

        e.DataSource = dt

    End Sub

    'Protected Sub ProjectCombo2_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles ProjectCombo2.InitializeDataSource

    '    Dim adap As New BasicDataTableAdapters.Projects1TableAdapter
    '    Dim dt As New BasicData.Projects1DataTable

    '    dt = adap.GetData(Val(Session("PlanYear")))
    '    ' Exit Sub
    '    e.DataSource = dt

    'End Sub

    Protected Sub WebGrid1_AddRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)
        Dim adapter As New CheckBudgetLimitTableAdapters.BudgetDetails1TableAdapter
        Dim id As Decimal
        'Dim adapter2 As New BasicDataTableAdapters.CmmtDetailsTableAdapter
        'Dim cmmt_id As Decimal = adapter2.GetCmmtId(Val(e.Row.Cells(2).Value))
        ' WebGrid1.ClientAction.Alert(e.Row.Cells(3).Value)
        Dim Cmmtcode As String
        Try
            Cmmtcode = e.Row.Cells(1).Value
        Catch ex As Exception
            Cmmtcode = ""

            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try

        Dim Actypecode As String
        Try
            Actypecode = e.Row.Cells(2).Value
        Catch ex As Exception
            Actypecode = ""
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try

        Dim ProDuctcode As String
        Try
            ProDuctcode = e.Row.Cells(3).Value
        Catch ex As Exception
            ProDuctcode = ""
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try
        Dim Prjcode As String
        Try
            Prjcode = e.Row.Cells(4).Value
        Catch ex As Exception
            Prjcode = ""
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try

        Dim TempFund As String
        Try
            TempFund = e.Row.Cells(12).Value
        Catch ex As Exception
            TempFund = ""
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try
        'If Cmmtcode.Replace(" ", "") = "" Then
        '    Cmmtcode = Nothing
        'End If
        'If Actypecode.Replace(" ", "") = "" Then
        '    Actypecode = Nothing
        'End If
        'If ProDuctcode.Replace(" ", "") = "" Then
        '    ProDuctcode = Nothing
        'End If
        Cmmtcode = Cmmtcode.Trim
        Actypecode = Actypecode.Trim
        ProDuctcode = ProDuctcode.Trim
        Prjcode = Prjcode.Trim


        Dim padap As New BasicDataTableAdapters.ProjectsTableAdapter
        Dim pfctr As String = padap.GetFCTR(Prjcode, Val(PlanYearsTxt.Text))
        id = adapter.InsertBudgetDetail(Val(PlanYearsTxt.Text), Val(PlanYearsTxt.Text), VersionTxt.Text, Nothing, Val(e.Row.Cells(9).Value), Val(e.Row.Cells(5).Value), Val(e.Row.Cells(6).Value), Val(e.Row.Cells(8).Value), "B03", If(TempFund = "", Nothing, TempFund), Nothing, Date.Now, Session("users"), Val(PlanYearsTxt.Text), If(Actypecode = "", Nothing, Actypecode), If(ProDuctcode = "", Nothing, ProDuctcode), Val(PlanYearsTxt.Text), e.Row.Cells(0).Value, Val(PlanYearsTxt.Text), If(Prjcode = "", Nothing, Prjcode), Val(PlanYearsTxt.Text), If(pfctr = "null", Nothing, e.Row.Cells(0).Value), Nothing, Nothing, If(Cmmtcode = "", Nothing, Cmmtcode), Val(PlanYearsTxt.Text), "")

        Dim dr As DataRow = e.Row.DataRow
        dr("Id") = id

        logger.Info("User " & Session("users") & " insert activity type " & Val(e.Row.Cells(3).Value) & " of fund center " & Val(e.Row.Cells(1).Value))
    End Sub

    Protected Sub WebGrid1_UpdateRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)
        'Exit Sub
        Dim id As Decimal
        id = e.Row.KeyValue
        Dim Cmmtcode As String
        Try
            Cmmtcode = e.Row.Cells(1).Value
            Cmmtcode = Cmmtcode.Trim
        Catch ex As Exception
            Cmmtcode = ""
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try
        Dim Actypecode As String
        Try
            Actypecode = e.Row.Cells(2).Value
            Actypecode = Actypecode.Trim
        Catch ex As Exception
            Actypecode = ""
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try
        Dim ProDuctcode As String
        Try
            ProDuctcode = e.Row.Cells(3).Value
            ProDuctcode = ProDuctcode.Trim
        Catch ex As Exception
            ProDuctcode = ""
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try
        Dim TmpFunded As String
        Try
            TmpFunded = e.Row.Cells(12).Value
        Catch ex As Exception
            TmpFunded = ""
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try
        Dim adapter As New CheckBudgetLimitTableAdapters.BudgetDetails1TableAdapter
        Dim adapter12 As New SplitData2TableAdapters.Budget12TableAdapter
        If Left(Actypecode, 1) = "9" Then
        Else
            adapter.UpdateBudgetLimit(Val(IIf(IsDBNull(e.Row.Cells(9).Value), 0, e.Row.Cells(9).Value)), _
                                      Val(IIf(IsDBNull(e.Row.Cells(5).Value), 0, e.Row.Cells(5).Value)), _
                                      Val(IIf(IsDBNull(e.Row.Cells(6).Value), 0, e.Row.Cells(6).Value)), _
                                      Val(IIf(IsDBNull(e.Row.Cells(8).Value), 0, e.Row.Cells(8).Value)), _
                                      If(String.IsNullOrEmpty(TmpFunded), Nothing, TmpFunded), _
                                      Date.Now, Session("users"), _
                                      If((Actypecode = ""), Nothing, Val(PlanYearsTxt.Text)), _
                                      If((Actypecode = ""), Nothing, e.Row.Cells(2).Value), _
                                      If((ProDuctcode = ""), Nothing, e.Row.Cells(3).Value), _
                                      If((ProDuctcode = ""), Nothing, Val(PlanYearsTxt.Text)), _
                                      If((Cmmtcode = ""), Nothing, e.Row.Cells(1).Value), _
                                      If((Cmmtcode = ""), Nothing, Val(PlanYearsTxt.Text)), " ", id)

            adapter12.DeleteBID(id)
        End If

        logger.Info("User " & Session("users") & " update activity type " & Val(IIf(IsDBNull(e.Row.Cells(3).Value), 0, e.Row.Cells(3).Value)) & " of fund center " & Val(IIf(IsDBNull(e.Row.Cells(1).Value), 0, e.Row.Cells(1).Value)))

        ' WebGrid1.ClientAction.Refresh()
    End Sub
    Sub PlotNode()

        Dim MyNode As WebTreeViewNode
        MyNode = New WebTreeViewNode()

        Dim adapter As New FundCenterParentTableAdapters.fctr_viewTableAdapter
        Dim dt As New FundCenterParent.fctr_viewDataTable
        dt = adapter.GetDataByUser(Session("users"), Val(PlanYearsTxt.Text))

        Dim root_id As String

        MyNode.Text = "GSB"
        MyNode.Value = "0"
        root_id = "0"

        If dt.Count > 0 Then

            WebTreeView3.Nodes.Add(MyNode)

            Dim rootpath = ""
            Dim prefil As String = ""
            prefil = Session("prefilter")
            rootpath = FctrClass.GetRootPrefil(Session("users"), Val(Session("planyear")), prefil)
            Dim rootarr() As String = Split(rootpath, ",")
            WebTreeView3.Nodes.Add(MyNode)

            For i = 0 To rootarr.Length - 1
                PlotChild(rootarr(i), MyNode, 1)
            Next
        End If

    End Sub

    Sub PlotChild(ByVal gpath As String, ByRef cnode As WebTreeViewNode, ByVal level As Decimal)
        'Response.Write(gpath & "<br>")
        Dim Hadapter As New FundCenterParentTableAdapters.FctHTableAdapter
        Dim Hdatatable As New FundCenterParent.FctHDataTable
        Hdatatable = Hadapter.GetDataByGPath(gpath, Val(Session("planyear")))

        Dim MyNode As WebTreeViewNode
        MyNode = New WebTreeViewNode()
        For Each row As FundCenterParent.FctHRow In Hdatatable


            MyNode.Text = row.Description
            MyNode.Value = row.FundCenter_FundCenterCode

            cnode.Nodes.Add(MyNode)
        Next


        If Len(gpath) >= 10 Then
            Exit Sub
        End If

        Dim hadap2 As New FundCenterParentTableAdapters.UserLikeGpathTableAdapter
        Dim hdt2 As New FundCenterParent.UserLikeGpathDataTable
        Dim sql As String = ""
        Dim prefil As String = ""
        prefil = Session("prefilter")

        Dim pathadd As String = "__"
        'For i = 1 To 4
        sql = ""
        Dim fullpath As String = gpath & pathadd
        If prefil <> "" Then
            sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        End If
        sql += " AND grouppath like '" & fullpath & "' "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND Fcth.PlanYear = " & Val(Session("PlanYear"))
        hadap2.GetDataByFilter(hdt2, sql)

        For Each row As FundCenterParent.UserLikeGpathRow In hdt2
            If Len(row.grouppath) <= 10 Then
                PlotChild(row.grouppath, MyNode, level + 1)
            End If

        Next

    End Sub


    Protected Sub SearhBtn_Click(sender As Object, e As ImageClickEventArgs) Handles SearhBtn.Click
        GenerateValues()
        If TabContainer1.ActiveTab.ID = TabPanel1.ID Then
            Session.Remove("search_fctr")
            If WebCombo1.Value <> "" And WebCombo2.Value <> "" Then
                Session.Add("search_fctr", FctrClass.GetFromToFundCenter(WebCombo1.Value, WebCombo2.Value, Session("users"), PlanYearsTxt.Text))
                'Response.Write(FctrClass.GetFromToFundCenter(WebCombo1.Value, WebCombo2.Value, Session("users")))
            ElseIf WebCombo1.Value <> "" And WebCombo2.Value = "" Then
                Session.Add("search_fctr", FctrClass.GetFromToFundCenter(WebCombo1.Value, WebCombo1.Value, Session("users"), PlanYearsTxt.Text))
                'Response.Write(FctrClass.GetFromToFundCenter(WebCombo1.Value, WebCombo1.Value, Session("users")))
            ElseIf WebCombo1.Value = "" And WebCombo2.Value <> "" Then
                Session.Add("search_fctr", FctrClass.GetFromToFundCenter(WebCombo2.Value, WebCombo2.Value, Session("users"), PlanYearsTxt.Text))
                'Response.Write(FctrClass.GetFromToFundCenter(WebCombo2.Value, WebCombo2.Value, Session("users")))
            Else
                Session.Add("search_fctr", Session("prefilter"))
            End If

        ElseIf TabContainer1.ActiveTab.ID = TabPanel2.ID Then
            Session.Remove("search_fctr")
            If WebCombo3.Value = "" Then
                Session.Add("search_fctr", Session("prefilter"))
            Else
                Session.Add("search_fctr", FctrClass.GetSubFundCenter(WebCombo3.Value, Session("users"), Session("Planyear"), Session("prefilter")))
            End If

        End If
        Session.Remove("Search")
        Session.Add("Search", "true")
        WebGrid1.ClearCachedDataSource()
        WebGrid1.RebindDataSource()
        FundCenterCombo.ClearCachedDataSource()
        FundCenterCombo.DataBind()
    End Sub

    Sub GenerateValues()
        If hdf1.Value.Length = 0 And hdf2.Value.Length = 0 Then
            Session("Search") = "false"
        End If
        Try
            Dim Numx As Array = hdf1.Value.Split(",")
            For i = 0 To Numx.Length - 1
                ms8.Items.FindByValue(Numx(i).ToString).Selected = True
            Next
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try
        Try
            Dim Numx2 As Array = hdf2.Value.Split(",")
            For j = 0 To Numx2.Length - 1
                ms9.Items.FindByValue(Numx2(j).ToString).Selected = True
            Next
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try

    End Sub




    Protected Sub WebGrid1_InitializePostBack(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.PostbackEventArgs)
        If e.Action = PostBackAction.Custom Then
            Dim ActionType As String = TryCast(Request("type"), String)
            If ActionType = "1" Then
                Dim checkedRows As ArrayList = WebGrid1.RootTable.GetCheckedRows()

                Dim adapter As New fundCenterTableAdapters.BudgetDetailsTableAdapter

                For Each keyValue As String In checkedRows

                    adapter.CoppyRow(keyValue)

                Next keyValue
            Else
                Dim adapter As New fundCenterTableAdapters.BudgetDetailsTableAdapter
                Dim adapter2 As New fundCenterTableAdapters.AttachmentsTableAdapter
                For Each keyValue As String In WebGrid1.RootTable.GetCheckedRows()
                    adapter2.DeleteAttach(keyValue)
                    adapter.DeleteRow(keyValue)
                    logger.Info("User " & Session("users") & " delete key " & keyValue)
                Next keyValue
            End If

            WebGrid1.ClientAction.Refresh()
        End If

    End Sub

    Protected Sub WebCombo1_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles WebCombo1.InitializeDataSource
        'If Session("Versions") > 1 Then
        'ds = PublicFunction.GetChild2(Session("users"))
        'ds.Tables(0).DefaultView.Sort = "FundCenterCode ASC"
        'e.DataSource = ds
        Dim adap As New BasicDataTableAdapters.FCTR_Child2TableAdapter
        Dim dt As New BasicData.FCTR_Child2DataTable
        Dim sql = ""
        Dim prefil As String = ""
        prefil = Session("prefilter")
        sql += " WHERE 1 = 1 "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FundCenters.PlanYear = " & Val(Session("PlanYear"))
        If prefil <> "" Then
            sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        End If
        sql += " and FundCenterHierarchies.PlanYear = " & Val(Session("PlanYear")) & " "
        sql += "ORDER BY FundCenterCode ASC"
        adap.GetDataByFilter(dt, sql)
        dt.Rows.Add("", "ทุกรายการ", "1", "0")
        dt.DefaultView.Sort = "FundCenterCode"
        e.DataSource = dt

        'Else
        'Dim adap As New BasicDataTableAdapters.FCTR_ChildTableAdapter
        'Dim dt As New BasicData.FCTR_ChildDataTable
        'dt = adap.GetOwnData(Session("FCTR"))
        'e.DataSource = dt
        'End If
    End Sub

    Protected Sub WebCombo2_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles WebCombo2.InitializeDataSource
        'If Session("Versions") > 1 Then
        'ds = PublicFunction.GetChild2(Session("users"))
        'ds.Tables(0).DefaultView.Sort = "FundCenterCode ASC"
        'e.DataSource = ds
        Dim adap As New BasicDataTableAdapters.FCTR_Child2TableAdapter
        Dim dt As New BasicData.FCTR_Child2DataTable
        Dim sql = ""
        Dim prefil As String = ""
        prefil = Session("prefilter")
        sql += " WHERE 1 = 1 "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FundCenters.PlanYear = " & Val(Session("PlanYear"))
        If prefil <> "" Then
            sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        End If
        sql += " and FundCenterHierarchies.PlanYear = " & Val(Session("PlanYear")) & " "
        sql += "ORDER BY FundCenterCode ASC"
        adap.GetDataByFilter(dt, sql)
        dt.Rows.Add("", "ทุกรายการ", "1", "0")
        dt.DefaultView.Sort = "FundCenterCode"
        e.DataSource = dt


        'Else
        'Dim adap As New BasicDataTableAdapters.FCTR_ChildTableAdapter
        'Dim dt As New BasicData.FCTR_ChildDataTable
        'dt = adap.GetOwnData(Session("FCTR"))
        'e.DataSource = dt
        'End If
    End Sub

    Protected Sub ActType_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles ActivityTypeCombo.InitializeDataSource

        Dim adap As New MassChangeDSTableAdapters.ActivityTypesTableAdapter
        Dim dt As New MassChangeDS.ActivityTypesDataTable

        dt = adap.GetData(Session("PlanYear"))

        e.DataSource = dt
        ' Response.Write(dt.Count)
    End Sub
    Protected Sub Product_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles ProductCombo.InitializeDataSource

        Dim adap As New MassChangeDSTableAdapters.ProductsTableAdapter
        Dim dt As New MassChangeDS.ProductsDataTable

        dt = adap.GetData(Session("PlanYear"))

        e.DataSource = dt

    End Sub
    Protected Sub Activity_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs)

        Dim adap As New MassChangeDSTableAdapters.ActivitiesTableAdapter
        Dim dt As New MassChangeDS.ActivitiesDataTable

        dt = adap.GetData(Session("PlanYear"))

        e.DataSource = dt

    End Sub

    Sub Alert(ByVal message As String)
        AlertText = "<script> alert('" & message & "');</script>"
    End Sub

    Protected Sub WebCombo4_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs)

        Dim adap As New MassChangeDSTableAdapters.CmmtsTableAdapter
        Dim dt As New MassChangeDS.CmmtsDataTable

        dt = adap.GetData(Session("PlanYear"))

        e.DataSource = dt



    End Sub
    Protected Sub WebCombo5_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs)

        Dim adap As New MassChangeDSTableAdapters.CmmtsTableAdapter
        Dim dt As New MassChangeDS.CmmtsDataTable

        dt = adap.GetData(Session("PlanYear"))

        e.DataSource = dt



    End Sub

    Protected Sub WebCombo3_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles WebCombo3.InitializeDataSource

        Dim adap As New FundCenterParentTableAdapters.SelectorTableAdapter
        Dim dt As New FundCenterParent.SelectorDataTable
        Dim dt2 As New FundCenterParent.SelectorDataTable
        Dim sql = ""
        Dim prefil As String = ""
        prefil = Session("prefilter")
        sql += " WHERE 1 = 1 "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FctH.PlanYear = " & Val(Session("PlanYear"))
        If prefil <> "" Then
            sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        End If
        sql += "ORDER BY Grouppath"
        adap.GetDataByFilter(dt2, sql)
        dt.Rows.Add("ทุกรายการ", "0", 0, "0", Val(Session("PlanYear")), "ทุกรายการ")
        dt.Merge(dt2)
        'dt.DefaultView.Sort = "FundCenter_FundCenterCode"
        e.DataSource = dt



    End Sub

End Class
